package com.demo.core.filter;

import com.demo.core.constants.TokenConstants;
import com.swak.common.util.UUIDHexGenerator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(((HttpServletRequest) request).getMethod())) {
            ((HttpServletResponse) response).setStatus(HttpStatus.OK.value());
            return;
        }
        try {
            RequestContext.setUserId("admin");
            // TODO 登录拦截，设置userId，直接RequestContext.getUserId();
            String token = getToken((HttpServletRequest) request);
            if(StringUtils.isNotEmpty(token)){
                String userId = JwtUtils.getUserId(token);
                if(StringUtils.isNotEmpty(userId)){
                    RequestContext.setUserId(userId);
                }
            }
            MDC.put("TRACE_ID", UUIDHexGenerator.generator());
            chain.doFilter(request, response);
        } finally {
            RequestContext.clear();
        }
    }


    /**
     * 获取请求token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }
}
